//
//  fawenlistViewController.m
//  tongxiangOASystem
//
//  Created by michael on 2018/4/3.
//  Copyright © 2018年 czd. All rights reserved.
//
#import "detailViewController.h"
#import "fawenlistViewController.h"
#import "LGLSearchBar.h"
#import "daibanTableViewCell.h"

#import "zfxqViewController.h"
#import "yjTableViewCell.h"
#import "zfyjViewController.h"
#import "UnDoneModel.h"
#import "OAUnDoneListCell.h"
#import "OAInBoxDetailViewController.h"
@interface fawenlistViewController ()
@property(nonatomic,strong)NSDictionary * adic;

@end

@implementation fawenlistViewController

- (void)viewDidLoad {
      self.view.backgroundColor = [UIColor colorWithHexString:@"efeff4"];
 LGLSearchBar * searchBar = [[LGLSearchBar alloc] initWithFrame:CGRectMake(0, 10, KScreenWidth, 40) searchBarStyle:LGLSearchBarStyleDefault];
[searchBar setSearchBarBordeWidth:0.1 bordColor:[UIColor clearColor] bordRadius:0];
//[searchBar setSearchBarImage:@"search" scale:30];
        [searchBar searchBarTextSearchTextBlock:^(NSString *searchText) {
        NSLog(@"%@", searchText);
        if (searchText.length>0) {
        _isSearching = @"yes";
    _searchstr = searchText;
//        [self loadSearchData];
    [_tableView headerBeginRefreshing];

}
     else{
[self.view makeToast:@"搜索关键字不能为空"];
}

    }];
    [self.view addSubview:searchBar];
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50+5, KScreenWidth,self.view.height-kTopHeight-55-LL_TabbarSafeBottomMargin) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.backgroundColor = [UIColor colorWithHexString:@"efeff4"];

_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
                 __weak typeof(self) weakSelf = self;

[self.tableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;
         if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchData];
}else{
        [weakSelf loadData]; //加载网络数据

}
    }];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self.tableView headerBeginRefreshing];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
        if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchMore];
}
     else {
     [weakSelf loadMore];
     }
        }else{
            
            [self.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
            
        }
        
    }];
    [super viewDidLoad];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshData" object:nil];
   
    // Do any additional setup after loading the view.
}
#pragma mark 搜素

- (void)loadSearchData{
    __weak typeof(self) weakSelf = self;
_currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
     [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"FilesDispatchSearch" success:^(id JSON) {
    NSLog(@"%@",JSON);

      if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
                self.totalCounts =[JSON[@"number"] intValue];
if(JSON[@"number"]){
self.title = [NSString stringWithFormat:@"发文查询(%@)",JSON[@"number"] ];
//   if (self.selectRowBlock) {
//  self.selectRowBlock(_titlename);
//  }
}else{
self.title  = @"发文查询";
//  if (self.selectRowBlock) {
//  self.selectRowBlock(_titlename);
//  }
}
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];

}
- (void)loadSearchMore{
    __weak typeof(self) weakSelf = self;

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
 [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"FilesDispatchSearch" success:^(id JSON) {

       NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

   self.totalCounts =[JSON[@"number"] intValue];


        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
     
    } failure:^(NSError *error) {

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
}
-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
        _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}
-(void)loadData{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

self.currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:kexchgregbookurl arrays:array method:@"regbookPage" success:^(id JSON) {
    NSLog(@"%@",JSON);
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
  self.totalCounts =[JSON[@"number"] intValue];

if(JSON[@"number"]){

       self.title = [NSString stringWithFormat:@"发文查询(%@)",JSON[@"number"] ];}

       else{

       self.title = @"发文查询";

       

       }
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        [self.tableView headerEndRefreshing];
        
    }];
    
}
-(void)refreshData{
    self.currentPage = 1;
    [self loadData];

}
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:kexchgregbookurl arrays:array method:@"regbookPage" success:^(id JSON) {
    
            NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

 self.totalCounts =[JSON[@"number"] intValue];

       self.title = [NSString stringWithFormat:@"发文查询(%@)",JSON[@"number"]        ];   self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"发送时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
             GDataXMLElement * isReadElement = [[data elementsForName:@"是否已读"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            model.isRead = [isReadElement stringValue];
            model.iconType = @"InBox"; //发送箱
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"发文查询(%d)",self.totalCounts];
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

  NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:14 minsWidth:60];

    return  titleFloat +10+10+20;

}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 static NSString *CellIdentifier = @"Cell";

    daibanTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[daibanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;


 }

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        NSDictionary *dic = self.dataArray[indexPath.row];
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     detailViewController * vc = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
    vc.type = @"shouwen";

    vc.fileId = dic[@"unid"];
            vc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:vc animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

